﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.UI.HtmlControls;
using System.Text;
using Marta.buchalska.wesele.Model;

namespace Marta.buchalska.wesele.Admin.Gallery
{
    public partial class Default : System.Web.UI.Page
    {
        //#region PageMethods
        //[WebMethod(EnableSession = true)]
        //public static string Echo()
        //{
        //    return "Echo";
        //}

        //[WebMethod(EnableSession = true)]
        //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        //public static AjaxResponce CreateCategory(string name)
        //{
        //    try
        //    {
        //        new Model.PhotoManager().CreateCategory(name);
        //    }
        //    catch (Exception ex)
        //    {
        //        return new AjaxResponce { Status = "ERROR", Message = "Nie udało się dodać nowej kategorii." + ex.Message };
        //    }
        //    return new AjaxResponce { Status = "OK", Message = "Dodano nową kategorię " + name };
        //}

        //[WebMethod(EnableSession = true)]
        //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        //public static AjaxResponce CreateGallery(string galleryName, int categoryId)
        //{
        //    try
        //    {
        //        new Model.PhotoManager().CreateGallery(galleryName, categoryId);
        //    }
        //    catch (Exception ex)
        //    {
        //        return new AjaxResponce { Status = "ERROR", Message = "Nie udało się dodać nowej gallerii." + ex.Message };
        //    }
        //    return new AjaxResponce { Status = "OK", Message = "Dodano nową gallerię " + galleryName };
        //}

        //[WebMethod(EnableSession = true)]
        //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        //public static AjaxDropDownItemsCollections GetAllCategories()
        //{
        //    var resoult = new AjaxDropDownItemsCollections();
        //    resoult.OptionstCollection = new List<AjaxDropDownItem>();
        //    var categories = new Model.PhotoManager().GetAllCategory();
        //    if (categories.Tables[0].Rows.Count > 0)
        //    {
        //        var row = categories.Tables[0].Rows;
        //        for (int i = 0; i < row.Count; i++)
        //        {
        //            resoult.OptionstCollection.Add(new AjaxDropDownItem() { ID = (row[i]["ID"] as Nullable<int>).Value, Text = row[i]["Name"] as string });
        //        }
        //    }
        //    resoult.Status = "OK";
        //    return resoult;
        //}

        //[WebMethod(EnableSession = true)]
        //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        //public static AjaxDropDownItemsCollections GetAllGallery()
        //{
        //    var resoult = new AjaxDropDownItemsCollections();
        //    resoult.OptionstCollection = new List<AjaxDropDownItem>();
        //    var galleries = new PhotoManager().GetAllGallery();
        //    if (galleries.Tables[0].Rows.Count > 0)
        //    {
        //        var row = galleries.Tables[0].Rows;
        //        for (int i = 0; i < row.Count; i++)
        //        {
        //            resoult.OptionstCollection.Add(new AjaxDropDownItem() { ID = (row[i]["gallery_id"] as Nullable<int>).Value, Text = row[i]["gallery_name"] as string });
        //        }
        //    }
        //    resoult.Status = "OK";
        //    return resoult;
        //}
        //#endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            LoadData();
        }

        protected void AddPhotoClick(object sender, EventArgs e)
        {
            try
            {
                var galleryId = Request["gallerySelect"] as string;

                if (galleryId != null)
                {
                    var filePath = new FileMeneger().SaveFile(photoPost, int.Parse(galleryId));
                    new Model.PhotoManager().InsertImage(
                        photoPost.PostedFile.FileName, string.Empty, filePath, int.Parse(galleryId));
                }
            }
            catch (Exception ex) { errorLabel.Text = ex.Message; }
        }

        private void LoadData()
        {
            var dbGatewey = new Model.DataBaseGateway();

            var photos = dbGatewey.Gallery.GetPhotos();
            if (photos.Tables[0].Rows.Count > 0)
            {
                photoView.DataSource = photos.Tables[0].Rows;
                photoView.DataBind();
            }

            var gallery = new Model.PhotoManager();
            var gallerys = gallery.GetAllGallery();
            StringBuilder text;
            StringBuilder value;

            if (gallerys.Tables[0].Rows.Count > 0)
            {
                photoGalleryList.DataSource = gallerys.Tables[0].Rows;
                photoGalleryList.DataBind();
                foreach (DataRow item in gallerys.Tables[0].Rows)
                {
                    galleryListDDL.Items.Add(new ListItem((string)item["gallery_name"], (item["gallery_id"]).ToString()));
                }
            }
        }

        protected void CategoryListItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var item = e.Item.DataItem as System.Data.DataRow;
            var catName = e.Item.FindControl("catName") as Label;
            var photocount = e.Item.FindControl("photoCount") as Label;

            catName.Text = item["photo_category_name"] as string;
            photocount.Text = string.Format("Zdjęć : {0}", ((int)item["photo_count"]).ToString());
        }

        protected void PhotoViewItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var image = e.Item.FindControl("imgSmall") as HtmlImage;
            var data = e.Item.DataItem as DataRow;
            if (data != null)
                if (image != null)
                    image.Src = data["photo_url"] as string;

            var originalImage = e.Item.FindControl("originalImage") as HtmlAnchor;
            if (originalImage != null)
                if (image != null)
                    originalImage.HRef = image.Src.Replace("mini", "original");

            var delete = e.Item.FindControl("deleteBtn") as LinkButton;
            if (delete != null)
            {
                delete.CommandName = "DeleteItem";
                delete.CommandArgument = data["photo_id"].ToString();
                delete.OnClientClick = "return confirm('Czy na pewno chcesz usunąć zdjęcie ? ');";
            }
        }

        protected void PhotoCategoryListItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var anchor = e.Item.FindControl("galleryFiltr") as Button;
            var data = e.Item.DataItem as DataRow;

            if (anchor != null)
            {
                if (data != null)
                {
                    anchor.Text = data["gallery_name"] as string;
                    anchor.CommandArgument = (data["gallery_id"]).ToString();
                }
            }
        }

        protected void FiltrPhotosClick(object sender, EventArgs eventArgs)
        {
            var lb = sender as Button;
            if (lb != null)
            {
                var ca = int.Parse(lb.CommandArgument);

                var photos = ca > 0 ? new PhotoManager().GetPhotosFromGallery(ca) : new PhotoManager().GetPhotos();

                photoView.DataSource = photos.Tables[0].Rows;
                photoView.DataBind();
            }
        }

        protected void PhotoViewItemCommand(object sender, ListViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DeleteItem": //TODO: Dodać funkcjonalności 
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// Usuwanie kategorii 
        /// </summary>
        /// <param name="sender">wyzwalacz</param>
        /// <param name="e">argument</param>
        protected void DeletePhotoClick(object sender, EventArgs e)
        {
            var button = sender as LinkButton;
            string photoId = button.CommandArgument;
            new PhotoManager().DeletePhoto(int.Parse(photoId));
        }
        protected void AddImage_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    var galleryId = galleryListDDL.SelectedValue;

                    if (galleryId != null)
                    {
                        var filePath = new FileMeneger().SaveFile(newImage, int.Parse(galleryId));
                        new Model.PhotoManager().InsertImage(
                            photoPost.PostedFile.FileName, string.Empty, filePath, int.Parse(galleryId));
                    }
                }
                catch (Exception ex) { errorLabel.Text = ex.Message; }
            }
        }
    }
}